package com.rocky.study.volatitle;

class myNumber {
    volatile int number = 0;

    // Q:如何保证原子性
    void addOne() {
        number++;
    }
}

public class VolatileDemo3 {
    public static void main(String[] args) {
        myNumber demo3 = new myNumber();
        System.out.println(Thread.currentThread().getName() + " come in number value:"+ demo3.number);
        for (int i = 1; i <= 20; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    demo3.addOne();
                }
            }, String.valueOf(i)).start();
        }
//        System.out.println(demo3.number);
        // 需要等待上面20个线程计算完成后,再用main线程取得最后的值看最终结果值是多少?
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + " finally number value:" + demo3.number);
    }

}
